package day01;

import java.util.Iterator;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/2/27 20:18
 */
public class DoublyLinkedListSentinel implements Iterable<Integer> {
    private static class Node {
        Node prev;
        int value;
        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    // 头尾哨兵
    private Node head;
    private Node tail;

    public DoublyLinkedListSentinel() {
        head = new Node(null, 666, null);
        tail = new Node(null, 888, null);
        head.next = tail;
        tail.prev = head;
    }

    /**
     * 根据索引位置 查找结点
     * @param index
     * @return
     */
    private Node findNode(int index) {
        int i = -1;
        for(Node p = head; p != tail; p = p.next, i++) {
            if (index == i) {
                return p;
            }
        }
        return null;
    }

    public void insert(int index, int value) {
        Node prev = findNode(index - 1);
        if (prev == null) {
            throw new RuntimeException("非法index!");
        }
        Node next = prev.next;
        Node inserted = new Node(prev, value, next);
        prev.next = inserted;
        next.prev = inserted;
    }

    public void addFirst(int value) {
        insert(0, value);
    }

    public void remove(int index) {
        Node prev = findNode(index - 1);
        if (prev == null) {
            throw new RuntimeException("非法index!");
        }
        Node removed = prev.next;
        // 待删除节点是尾哨兵
        if (removed == tail) {
            throw new RuntimeException("非法index!");
        }
        prev.next = removed.next;
        removed.next.prev = prev;
    }

    public void removeFirst() {
        remove(0);
    }

    public void addLast(int value) {
        Node last = tail.prev;
        last.next = new Node(last, value, tail);
        tail.prev = last.next;
    }

    public void removedLast() {
        Node removed = tail.prev;
        if (removed == head) {
            throw new RuntimeException("没有可删除节点!");
        }
        removed.prev.next = tail;
        tail.prev = removed.prev;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = head.next;
            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public Integer next() {
                int v = p.value;
                p = p.next;
                return v;
            }
        };
    }
}
